<script setup lang="ts">
import { ProjectForm } from '@/api/exam/project/types';
import { h } from 'vue';
import {
  CloseOutlined,
  DeleteOutlined,
  EditOutlined,
  FullscreenExitOutlined,
  FullscreenOutlined,
  PlusOutlined, PrinterOutlined,
  ReloadOutlined
} from '@ant-design/icons-vue';
import { delAnswer, listAnswer, pageAnswer } from '@/api/exam/answer';
import { AnswerVO } from '@/api/exam/answer/types';
import DataEdit from '@/views/exam/project/info/dataEdit.vue';
import DataManual from '@/views/exam/project/info/dataManual.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

interface Props {
  projectForm: any | ProjectForm;
}

// 定义组件 Props，并设置默认值
const props = withDefaults(defineProps<Props>(), {
  projectForm: {
    setting: {}
  }
});

// 将父组件传递的 projectForm 转换为响应式对象，并监听其变化
const projectForm = ref<ProjectForm>(props.projectForm);
watch(() => props.projectForm, () => {
  projectForm.value = props.projectForm; // 当父组件更新时同步更新本地引用
});

const loading = ref(false);
const answerPage = ref<AnswerVO[]>([]);
const answerList = ref<AnswerVO[]>([]);
const total = ref(0);
const queryParams = ref({
  pageNum: 1,
  pageSize: 20,
  projectId: projectForm.value.id,
});
const queryParams2 = ref({
  pageNum: 1,
  pageSize: 20,
  projectId: projectForm.value.id,
  tempSave: '1'
});
const getAnswerPage = async () => {
  loading.value = true;
  const res = await pageAnswer(queryParams.value);
  answerPage.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
const manualLoading = ref(false);
const getAnswerList = async () => {
  manualLoading.value = true;
  const res = await listAnswer(queryParams2.value);
  answerList.value = res.data;
  manualLoading.value = false;
};
const tableContainer = ref(null);
const tableHeight = ref(400);
// 计算表格高度
const calculateTableHeight = () => {
  nextTick(() => {
    if (!tableContainer.value) return;
    // 获取视口高度和表格容器位置
    const screenHeight = window.innerHeight;
    const { top } = tableContainer.value.getBoundingClientRect();
    // 计算可用高度（视口高度 - 表格到视口顶部距离 - 底部边距）
    const bottomPadding = 130;
    let height = screenHeight - top - bottomPadding;

    // 设置最小高度防止异常
    tableHeight.value = Math.max(height, 400);
  });
};

const columns = ref<any>([
  {
    title: '序号', dataIndex: 'index', key: 'index', align: 'center', width: 80,
    customRender({ text, record, index, column }) {
      return index + 1 + (queryParams.value.pageNum - 1) * queryParams.value.pageSize;
    }
  },
  { title: '状态', dataIndex: 'tempSave', key: 'tempSave', align: 'center', width: 80 },
  { title: '分数', dataIndex: 'examScore', key: 'examScore', align: 'center', width: 80 },
  { title: '开始时间', dataIndex: ['metaInfo', 'answerInfo', 'startTime'], align: 'center', width: 180 },
  { title: '提交时间', dataIndex: ['metaInfo', 'answerInfo', 'endTime'], align: 'center', width: 180 },
  { title: '提交人', dataIndex: ['user', 'userName'], align: 'center', width: 120 },
  { title: 'IP地址', dataIndex: ['metaInfo', 'clientInfo', 'remoteIp'], align: 'center', width: 120 },
  {
    title: '浏览器',
    key: 'browser',
    dataIndex: ['metaInfo', 'clientInfo', 'browser'],
    align: 'center',
    width: 200,
    ellipsis: true
  },
  { title: '设备类型', dataIndex: ['metaInfo', 'clientInfo', 'deviceType'], align: 'center', width: 120 },
  { title: '平台类型', key: 'platform', dataIndex: ['metaInfo', 'clientInfo', 'platform'], align: 'center', width: 120 }
]);

const selectedRowKeys = ref<string[]>([]);
const selectedRows = ref<AnswerVO[]>([]);
// 行选择配置
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: string[], rows: AnswerVO[]) => {
    selectedRowKeys.value = keys;
    selectedRows.value = rows;
    console.log(selectedRowKeys.value);
    console.log(selectedRows.value);
  },
  onSelectAll: (selected: boolean, selectedRows: AnswerVO[], changeRows: AnswerVO[]) => {
  }
}));
// 自定义行点击选中
const currentRow = ref<AnswerVO>();
const handleRowClick = (record: AnswerVO) => {
  selectedRowKeys.value = [];
  selectedRowKeys.value = [record.id];
  currentRow.value = record;
};

// 数据编辑、添加、删除等操作
const resetData = () => {
  selectedRowKeys.value = [];
  currentRow.value = null;
  getAnswerPage();
};
const addData = () => {

};
const editData = () => {
  if (judgeStatus()) {
    dialog.title = '数据详情';
    dialog.visible = true;
  } else {
    proxy?.$modal.notifyError('不可编辑');
  }
};

const manualData = async () => {
  if (judgeStatus()) {
    await getAnswerList().finally(
      () => {
        drawer.title = projectForm.value.name;
        drawer.visible = true;
      }
    );
  } else {
    proxy?.$modal.notifyError('不可评分');
  }

};
const judgeStatus = () => {
  if (currentRow.value.tempSave === '1') {
    return true;
  }
  return false;
};
const deleteData = async () => {
  const length = selectedRowKeys.value.length;
  await proxy?.$modal.modal('<strong>删除数据</strong><br/>确认删除这 ' + `<font color="red"> ${length}</font>` + ' 条数据吗？', '')
    .finally(() => loading.value = false);
  await delAnswer(selectedRowKeys.value);
  proxy?.$modal.notifySuccess('删除成功');
  resetData();
};

//根据项目survey获取表格列
const getColumns = () => {
  // 如果项目设置中开启了随机问题，那么不获取列
  if (projectForm.value.setting.examSetting.randomProject) {
    return [];
  }
  projectForm.value.survey.children.forEach((item: any) => {
  });
};

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const drawer = reactive<DrawerOption>({
  visible: false,
  title: ''
});
onMounted(async () => {
  calculateTableHeight();
  window.addEventListener('resize', calculateTableHeight);
  await getAnswerPage();
});
onBeforeUnmount(() => {
  window.removeEventListener('resize', calculateTableHeight);
});
</script>

<template>
  <el-container class="data-container">
    <el-header class="project-header data-header">
      <a-flex gap="small">
        <el-tooltip content="刷新数据">
          <a-button @click="resetData" :icon="h(ReloadOutlined)" />
        </el-tooltip>
        <a-button :icon="h(PlusOutlined)" :disabled="true"
                  @click="addData">添加
        </a-button>
        <a-button :icon="h(EditOutlined)" type="text" :disabled="selectedRowKeys.length!==1"
                  @click="editData">编辑
        </a-button>
        <a-button :icon="h(DeleteOutlined)" danger :disabled="selectedRowKeys.length === 0"
                  :loading="loading" @click="deleteData">删除
        </a-button>
        <a-button type="text" :disabled="selectedRowKeys.length!==1"
                  :loading="manualLoading" @click="manualData">
          <template #icon>
            <svg-icon icon-class="manual-ranking" class="mr-2" />
          </template>
          人工评分
        </a-button>
      </a-flex>
    </el-header>
    <el-main class="data-main">
      <div ref="tableContainer" :style="{height: tableHeight+55+'px'}">
        <a-table :data-source="answerPage" :columns="columns" row-key="id" :pagination="false"
                 :scroll="{x:true, y: tableHeight }" :loading="loading" :row-selection="rowSelection"
                 :custom-row="record => ({ onClick: () => handleRowClick(record) })">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key==='tempSave'">
              <span v-if="record.tempSave==='1'"> <a-badge status="success" />已完成</span>
              <span v-else> <a-badge status="processing" />进行中</span>
            </template>
            <template v-if="column.key==='browser'">
              {{ record.metaInfo.clientInfo.browser }} {{ record.metaInfo.clientInfo.browserVersion }}
            </template>
            <template v-if="column.key==='platform'">
              {{ record.metaInfo.clientInfo.platform }} {{ record.metaInfo.clientInfo.platformVersion }}
            </template>
          </template>
        </a-table>
      </div>
      <a-flex justify="center" align="center" style="height: 70px;">
        <pagination
          v-show="total>0"
          v-model:limit="queryParams.pageSize"
          v-model:page="queryParams.pageNum"
          :total="total"
          @pagination="getAnswerList" />
      </a-flex>
    </el-main>
  </el-container>
  <data-edit :answer="currentRow" :dialog="dialog" @edit-close="dialog.visible = false" />
  <data-manual :drawer="drawer" :answer-list="answerList" @manual-close="drawer.visible = false" />
</template>

<style scoped lang="scss">
.data-header {
  display: flex;
  align-items: center;
  background-color: var(--fixedHeaderBg);
  gap: 8px;
}

.data-main {
  padding: 0;
}
</style>
<style lang="scss">
.data-container {
  background-color: var(--fixedHeaderBg);
}
</style>
